package com.example.elm.Account

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.Public.AccountInfo
import com.example.elm.Public.MyApplication
import com.example.elm.R
import com.example.elm.databinding.HeadChangeBinding
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URLEncoder
import kotlin.concurrent.thread

private val head = ArrayList<String>()
private var chose:String = ""
class HeadchangeActivity : ComponentActivity() {
    private lateinit var binding: HeadChangeBinding
    private lateinit var adapter: HeadAdapter
    private val server_ip = MyApplication.serverIp
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = HeadChangeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val AccountInformation = CommonUtil.getSerializable(this, "info", AccountInfo::class.java)
        val old = AccountInformation
        init_head()

        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding.headUi.layoutManager = layoutManager
        adapter = HeadAdapter(head) { selectedHead ->
            // 回调方法，更新 chosehead
            val headResId = resources.getIdentifier(
                "head${selectedHead}",
                "drawable",
                packageName
            )
            binding.chosehead.setImageResource(headResId)
        }
        binding.headUi.adapter = adapter

        if (AccountInformation.account == ""){
            binding.myhead.setImageResource(R.drawable.head0)
        }
        else{
            val headResId = resources.getIdentifier(
                "head${AccountInformation.head_image}",
                "drawable",
                this.packageName
            )
            binding.myhead.setImageResource(headResId)
        }

        binding.back.setOnClickListener {
            val intent = Intent()
            intent.putExtra("info", old)
            setResult(RESULT_OK, intent)
            finish()
        }

        binding.changeButton.setOnClickListener {
            if (AccountInformation.account == ""){
                Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show()
            }
            else{
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show()
                val new = AccountInfo(AccountInformation.account, AccountInformation.password, AccountInformation.name,
                    AccountInformation.people_name, chose, AccountInformation.introduction)
                update_head(new)
                val intent = Intent()
                intent.putExtra("info", new)
                setResult(RESULT_OK, intent)
                finish()
            }

        }
    }

    private fun init_head() {
        head.clear()
        head.add("0")
        head.add("1")
        head.add("2")
        head.add("3")
        head.add("4")
        head.add("5")
        head.add("6")
        head.add("7")
        head.add("8")
    }

    private class HeadAdapter(
        val head: ArrayList<String>,
        private val onHeadSelected: (String) -> Unit // 回调接口
    ) : RecyclerView.Adapter<HeadAdapter.ViewHolder>() {
        private var selectedPosition = -1 // 记录选中位置

        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val headForChoose: ImageView = view.findViewById(R.id.head_for_chose)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.head_ui, parent, false)
            val viewHolder = ViewHolder(view)
            viewHolder.itemView.setOnClickListener {
                val position = viewHolder.absoluteAdapterPosition
                selectedPosition = position
                chose = head[position] // 更新全局的选择
                onHeadSelected(chose) // 通过回调通知活动
                notifyDataSetChanged() // 刷新列表，显示选中状态
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val headResId = holder.itemView.context.resources.getIdentifier(
                "head${head[position]}",
                "drawable",
                holder.itemView.context.packageName
            )
            holder.headForChoose.setImageResource(headResId)

            // 更新选中状态
            holder.itemView.isSelected = (position == selectedPosition)
        }

        override fun getItemCount(): Int = head.size
    }

    //连接服务器，更新头像
    fun update_head(info: AccountInfo){
        val jsp = "http://$server_ip:8080/Account/change_Head.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val requestBody = FormBody.Builder()
                    .add("phone", URLEncoder.encode(info.account, "UTF-8"))
                    .add("head_image", URLEncoder.encode(info.head_image, "UTF-8"))
                    .build()
                val request: Request = Request.Builder()
                    .url(jsp)
                    .post(requestBody)
                    .build()
            }
            catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
}